package menu

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RemoveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRemoveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemoveLogic {
	return &RemoveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RemoveLogic) Remove(req *types.MenuRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)

	//1.菜单是否存在
	_, err = l.svcCtx.MenuModel.FindOne(l.ctx, req.Id)
	switch err {
	case nil:

	case model.ErrNotFound:
		resp.Code = http.StatusBadRequest
		resp.Msg = "路由不存在"
		return resp, nil
	default:
		fmt.Printf("[Error]查询路由[%d]:%s\n", req.Id, err.Error())
		resp.Code = http.StatusBadRequest
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.菜单是否有子菜单
	total, err := l.svcCtx.MenuModel.Count(l.ctx, fmt.Sprintf(" where parent_id=%d", req.Id))
	switch err {
	case nil:
	case model.ErrNotFound:
	default:
		fmt.Printf("[Error]查询路由[%d]子菜单:%s\n", req.Id, err.Error())
		resp.Code = http.StatusBadRequest
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	if total > 0 {
		resp.Code = http.StatusBadRequest
		resp.Msg = "当前菜单含有子菜单，不能删除"
		return resp, nil
	}

	//3.删除菜单
	err = l.svcCtx.MenuModel.Delete(l.ctx, req.Id)
	if err != nil {
		fmt.Printf("[Error]删除路由[%d]:%s\n", req.Id, err.Error())
		resp.Code = http.StatusBadRequest
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
